import 'package:flutter/material.dart';
import 'package:fluttertest/screens/delivery/summary_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../models/task_model.dart';
import '../../utils/http_client.dart';
import '../../utils/logger.dart';
import 'task_detail_screen.dart';

class CompletedTasksScreen extends StatefulWidget {
  const CompletedTasksScreen({super.key});

  @override
  State<CompletedTasksScreen> createState() => _CompletedTasksScreenState();
}

class _CompletedTasksScreenState extends State<CompletedTasksScreen> {
  final List<TaskModel> _tasks = [];
  final ScrollController _scrollController = ScrollController();
  bool _isLoading = false;
  bool _hasMore = true;
  int _currentPage = 1;
  static const int _pageSize = 10;

  @override
  void initState() {
    super.initState();
    _loadTasks();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      if (!_isLoading && _hasMore) {
        _loadTasks();
      }
    }
  }

  Future<void> _loadTasks() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final prefs = await SharedPreferences.getInstance();
      final userId = prefs.getString('savedJobNumber');

      final response = await HttpClient.dio.post(
        '/follower/getNewTasked',  // 使用已完成任务的API
        data: {
          'userid': userId,
          'date': DateTime.now().toString().split(' ')[0],
          'page': _currentPage,
          'totle': _pageSize,
        },
      );
      print(response.data);
      if (response.data['code'] == 0) {
        final List<dynamic> tasksJson = response.data['data']['tasked'] ?? [];
        final List<TaskModel> newTasks = tasksJson.map((json) => TaskModel.fromJson(json)).toList();

        setState(() {
          _tasks.addAll(newTasks);
          _currentPage++;
          _hasMore = newTasks.isNotEmpty && newTasks.length >= _pageSize;
          _isLoading = false;
        });
      } else {
        setState(() {
          _hasMore = false;
          _isLoading = false;
        });
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '加载失败')),
          );
        }
      }
    } catch (e) {
      Logger.e('Load tasks error', e);
      setState(() {
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
    }
  }

  Future<void> _refresh() async {
    setState(() {
      _tasks.clear();
      _currentPage = 1;
      _hasMore = true;
    });
    await _loadTasks();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('已完成的任务'),
      ),
      body: RefreshIndicator(
        onRefresh: _refresh,
        child: ListView.builder(
          controller: _scrollController,
          padding: const EdgeInsets.all(16),
          itemCount: _tasks.length + 1,
          itemBuilder: (context, index) {
            if (index == _tasks.length) {
              return _buildLoadingIndicator();
            }

            final task = _tasks[index];
            return Card(
              margin: const EdgeInsets.only(bottom: 16),
              child: InkWell(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => SummaryScreen(
                        waybillNumber: task.waybillNumber,
                      ),
                    ),
                  );
                },
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            task.carCode,
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          _buildStatusChip("已完成"),
                        ],
                      ),
                      const Divider(height: 16),
                      _buildInfoRow('查询人', task.driverName),
                      const SizedBox(height: 8),
                      _buildInfoRow('单据来源', task.centerCode==9900?'常温':task.centerCode==9901?'冷藏':'冷冻'),
                      const SizedBox(height: 8),
                      _buildInfoRow('创建时间', task.createTime),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child: _hasMore
          ? const CircularProgressIndicator()
          :_tasks.isEmpty
            ? const Text('暂无任务')
            : _hasMore
            ? const CircularProgressIndicator()
            : const Text('没有更多任务了'),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Row(
      children: [
        SizedBox(
          width: 80,
          child: Text(
            label,
            style: const TextStyle(
              color: Colors.grey,
              fontSize: 14,
            ),
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: const TextStyle(fontSize: 14),
          ),
        ),
      ],
    );
  }

  Widget _buildStatusChip(String status) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.green.withOpacity(0.1),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.green),
      ),
      child: Text(
        status,
        style: const TextStyle(
          color: Colors.green,
          fontSize: 12,
        ),
      ),
    );
  }
} 